const session = require('koa-session')
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const koaBody = require('koa-body')({multipart: true})
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const { SESSION_SIGNED_KEY, SESSION_CONFIG } = require('./config')
const connect = require('./mongodb/index')

const rsa = require('./routes/rsa');                  // rsa模块
const file = require('./routes/file');                // 文件模块
const user = require('./routes/user');                // 用户模块
const article = require('./routes/article');          // 文章模块
const menu = require('./routes/menu');                // 菜单模块
const comment = require('./routes/comment');          // 评论留言模块

// error handler
onerror(app)

// middlewares
app.use(koaBody);
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// session
app.keys = SESSION_SIGNED_KEY;
app.use(session(SESSION_CONFIG, app));

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

app.use(rsa.routes(), rsa.allowedMethods());      // rsa模块
app.use(file.routes(), file.allowedMethods());            // 文件模块
app.use(user.routes(), user.allowedMethods());            // 用户模块
app.use(article.routes(), article.allowedMethods());      // 文章模块
app.use(menu.routes(), menu.allowedMethods());            // 菜单模块
app.use(comment.routes(), comment.allowedMethods());      // 评论留言模块

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
  ctx.body = {code: 0, data: null, msg: err.message}
});

//立即执行函数
(async () => {
  //执行连接数据库任务
  await connect()
})()

module.exports = app
